package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import entity.Employee;

@Repository("employeeDao")
public class EmployeeDao {

	@Resource(name = "jt")
	private JdbcTemplate jt;

	public void save(Employee e) {

		String sql = "insert into t_emp " + "values(t_emp_seq.nextval,?,?)";

		Object[] args = { e.getName(), e.getAge() };

		jt.update(sql, args);

	}

	//通过ID查询
	public Employee findById(int id) {

		String sql = "select *from t_emp " + "where id=?";

		Object[] args = { id };

		Employee emp = null;

		try {
			emp = jt.queryForObject(sql, args, new EmpRowMapper());
			return emp;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return emp;
		}

	}

	//查询数据
	public List<Employee> findAll() {

		String sql = "select *from t_emp";
		return jt.query(sql, new EmpRowMapper());

	}

	//修改数据
	public void modify(Employee e){
		
		String sql="UPDATE T_EMP "
				+ "SET NAME=?,AGE=? WHERE ID=?";
		
		Object[]args={e.getName(),e.getAge(),e.getId()};
		
		jt.update(sql, args);
		
	}
	
	//删除数据
	public void delete(int id){
		String sql="DELETE FROM T_EMP "
				+ "WHERE ID=?";
		
		Object[] args={id};
		
		jt.update(sql,args);
		
		
	}
	
	
	
	

	// 封装了对结果集的处理
	class EmpRowMapper implements RowMapper<Employee> {

		/*
		 * 告诉JdbcTemplate,如何将一条记录转换成已给实体对象.
		 *  index:正在被处理的记录的下标
		 * 
		 */
		public Employee mapRow(ResultSet rs, int index) throws SQLException {

			Employee emp = new Employee();
			emp.setId(rs.getInt("id"));
			emp.setName(rs.getString("name"));
			emp.setAge(rs.getInt("age"));

			return emp;

		}

	}

}
